<template>
  <div class="doc-categories-page">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">文档分类管理</h2>
      <div class="page-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建分类
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true">
        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入分类名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="文档源">
          <el-select v-model="searchForm.docSource" clearable>
            <el-option label="全部" value="" />
            <el-option label="Cursor 文档" value="cursor" />
            <el-option label="其他文档" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 分类树形表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      row-key="id"
      :tree-props="{ children: 'children' }"
      default-expand-all
      border
    >
      <el-table-column prop="name" label="分类名称" min-width="200">
        <template #default="{ row }">
          <el-icon v-if="row.icon" class="category-icon">
            <component :is="row.icon" />
          </el-icon>
          {{ row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="slug" label="URL标识" width="150" />
      <el-table-column prop="docSource" label="文档源" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.docSource" size="small">
            {{ row.docSource }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序" width="80" align="center" />
      <el-table-column label="文档数" width="80" align="center">
        <template #default="{ row }">
          <el-tag>{{ row.lessonsCount || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.isActive"
            :disabled="!row.isDocCategory"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            link
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="!row.children?.length"
            type="success"
            size="small"
            link
            @click="handleAddChild(row)"
          >
            添加子分类
          </el-button>
          <el-button
            v-if="!row.lessonsCount && row.isDocCategory"
            type="danger"
            size="small"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分类表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="URL标识" prop="slug">
          <el-input v-model="formData.slug" placeholder="请输入URL标识" />
        </el-form-item>
        <el-form-item label="上级分类">
          <el-cascader
            v-model="formData.parentId"
            :options="categoryOptions"
            :props="cascaderProps"
            clearable
            placeholder="请选择上级分类"
          />
        </el-form-item>
        <el-form-item label="文档源" prop="docSource">
          <el-select v-model="formData.docSource">
            <el-option label="Cursor 文档" value="cursor" />
            <el-option label="其他文档" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="formData.sortOrder" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import { useDocsStore } from '@/stores/docs'
import type { DocCategory } from '@/types/docs'

const docsStore = useDocsStore()

// 状态
const loading = ref(false)
const tableData = ref<DocCategory[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editId = ref<number | null>(null)
const formRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  name: '',
  docSource: ''
})

// 表单数据
const formData = reactive<Partial<DocCategory>>({
  name: '',
  slug: '',
  description: '',
  parentId: null,
  docSource: 'cursor',
  sortOrder: 0,
  isDocCategory: true
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { max: 100, message: '分类名称不能超过100个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入URL标识', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: 'URL标识只能包含小写字母、数字和横线', trigger: 'blur' }
  ],
  docSource: [
    { required: true, message: '请选择文档源', trigger: 'change' }
  ]
}

// 级联选择器配置
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true,
  emitPath: false
}

// 分类选项（用于级联选择器）
const categoryOptions = ref<any[]>([])

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    await docsStore.fetchDocCategories()
    // 只显示文档分类
    tableData.value = docsStore.categoryTree.filter(cat => cat.isDocCategory)
    updateCategoryOptions()
  } catch (error) {
    ElMessage.error('加载分类数据失败')
  } finally {
    loading.value = false
  }
}

// 更新分类选项
const updateCategoryOptions = () => {
  const buildOptions = (categories: DocCategory[]): any[] => {
    return categories.map(cat => ({
      id: cat.id,
      name: cat.name,
      children: cat.children ? buildOptions(cat.children) : undefined
    }))
  }
  categoryOptions.value = buildOptions(tableData.value)
}

// 搜索
const handleSearch = () => {
  // 实现搜索逻辑
  loadData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.docSource = ''
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 创建分类
const handleCreate = () => {
  dialogTitle.value = '新建文档分类'
  editId.value = null
  dialogVisible.value = true
}

// 添加子分类
const handleAddChild = (row: DocCategory) => {
  dialogTitle.value = `添加子分类 - ${row.name}`
  editId.value = null
  formData.parentId = row.id
  formData.docSource = row.docSource || 'cursor'
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row: DocCategory) => {
  dialogTitle.value = '编辑文档分类'
  editId.value = row.id
  Object.assign(formData, {
    name: row.name,
    slug: row.slug,
    description: row.description,
    parentId: row.parentId,
    docSource: row.docSource,
    sortOrder: row.sortOrder
  })
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (row: DocCategory) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    await docsStore.deleteDocCategory(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    // 用户取消或删除失败
  }
}

// 状态切换
const handleStatusChange = async (row: DocCategory) => {
  try {
    await docsStore.updateDocCategory(row.id, { isActive: row.isActive })
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.isActive = !row.isActive // 恢复原状态
    ElMessage.error('状态更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (editId.value) {
        await docsStore.updateDocCategory(editId.value, formData)
        ElMessage.success('更新成功')
      } else {
        await docsStore.createDocCategory(formData)
        ElMessage.success('创建成功')
      }
      dialogVisible.value = false
      loadData()
    } catch (error) {
      ElMessage.error(editId.value ? '更新失败' : '创建失败')
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    name: '',
    slug: '',
    description: '',
    parentId: null,
    docSource: 'cursor',
    sortOrder: 0,
    isDocCategory: true
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.doc-categories-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin: 0;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  background: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.category-icon {
  margin-right: 8px;
  vertical-align: middle;
}
</style> 